package com.artup.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.artup.common.Constants;
import com.artup.common.ResponseResult;
import com.artup.dao.UserDao;
import com.artup.pojo.User;
import com.artup.service.UserService;
import com.artup.util.CommonUtils;
import com.artup.util.file.PropertiesUtils;

/**
 * 用户
 * @author hapday
 * @date 2017年9月4日 @Time 上午9:58:27
 */
@Service( value = "userService" )
@Transactional( readOnly = false )
public class UserServiceImpl implements UserService {
	private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
	
	@Autowired
	private UserDao userDao;

	@Override
	public ResponseResult queryUserById(long id) {
		LOGGER.info("id = {}", id);
		ResponseResult responseResult = new ResponseResult();
		
		User user = null;
		try {
			user = this.userDao.selectUserById(id);

			responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
			responseResult.setMessage("根据【ID】查询【用户】  - 成功。");
			responseResult.setData(user);
		} catch (Exception e) {
			LOGGER.error("根据【ID】查询【用户】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
			responseResult.setMessage("根据【ID】查询【用户】  - 成功。");
		}

		return responseResult;
	}

	/*@Override
	public ResponseResult queryUserList(User user) {
		ResponseResult responseResult = new ResponseResult();
		
		ObjectMapper mapper = new ObjectMapper();
		try {
			LOGGER.info("user = " + mapper.writeValueAsString(user));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		
		List<User> userList = null;
		try {
			userList = this.userDao.selectUserList(user);
			
			responseResult.setStatus(1);
			responseResult.setMessage("模糊查询【用户列表】 - 成功。");
			responseResult.setData(userList);
		} catch (Exception e) {
			LOGGER.error("模糊查询【用户列表】 - 失败！", e);
			
			responseResult.setStatus(2);
			responseResult.setMessage("模糊查询【用户列表】 - 失败！");
		}
		
		return responseResult;
	}*/

	@Override
	public ResponseResult queryUserList(User user) {
		LOGGER.info("user = {}", JSONArray.toJSONString(user));
		
		// 定义返回的结果集
		ResponseResult responseResult = new ResponseResult();

		// 设置初始条件
		if (null != user) {
			if (CommonUtils.isNotEmpty(user.getBeginLastLoginTime())) {
				user.setBeginLastLoginTime(user.getBeginLastLoginTime()
						+ " 00:00:00");
			}
			if (CommonUtils.isNotEmpty(user.getEndLastLoginTime())) {
				user.setEndLastLoginTime(user.getEndLastLoginTime()
						+ " 23:59:59");
			}
		}

		// 模糊查询【用户】总记录数
		long totalCount = 0;
		try {
			totalCount = this.userDao.selectUserTotalCount(user);
		} catch (Exception e) {
			LOGGER.error("模糊查询【用户】总记录数 - 失败！", e);
		}
		
		if(0 == totalCount) {
			responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
			responseResult.setMessage("无订单。");
			
			return responseResult;
		}

		Map<String, Object> resultMap = new HashMap<String, Object>(); // 结果集
		resultMap.put("totalCount", totalCount);
		
		if(null == user.getPageIndex() || 0 >= user.getPageIndex()) {
			user.setPageIndex(1);
		}
		if(null == user.getPageSize() || 0 >= user.getPageSize()) {
			user.setPageSize(Integer.valueOf(PropertiesUtils.getValue("pagination.pageSize")));
		}
		
		user.setOffset( (long) ( (user.getPageIndex() - 1) * user.getPageSize() ) ); // 设置分页的偏移量，即起始记录数

		// 模糊查询【用户】列表
		List<User> userList = null;
		try {
			userList = this.userDao.selectUserList(user);
		} catch (Exception e) {
			LOGGER.error("模糊查询【用户】列表 - 失败！", e);
		}
		
		if(CommonUtils.isNotEmpty(userList)) {
			for(User user_ : userList) {
				if(null == user_)
					continue;
				
				if(-1 == user_.getSex() || 0 == user_.getSex()){
					user_.setSexName("未知");
				} else if(1 == user_.getSex()){
					user_.setSexName("男");
				} else if(2 == user_.getSex()){
					user_.setSexName("女");
				}
				
				if(StringUtils.isNotBlank(user_.getBirthday())) {
					user_.setBirthday(user_.getBirthday().substring(0, 10));
				}
			}
		}

		resultMap.put("userList", userList);// 返回的总数据

		// 设置返回的结果集
		responseResult.setData(resultMap);
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("模糊查询【用户】列表 - 成功。");

		// 回结果集
		return responseResult;
	}

	@Override
	public ResponseResult saveUser(User user) {
		LOGGER.info("user = " + JSONObject.toJSONString(user));
		ResponseResult responseResult = new ResponseResult();
		
		if(null != user) {
			try {
				this.userDao.insertUser(user);
				
				responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
				responseResult.setMessage("保存【用户】 - 成功。");
			} catch (Exception e) {
				LOGGER.error("保存【用户】 - 失败！", e);
				
				responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
				responseResult.setMessage("保存【用户】 - 失败！");
			}
		}
		
		return responseResult;
	}
	
	@Override
	public ResponseResult updateUserById(User user) {
		LOGGER.info("user = " + JSONObject.toJSONString(user));
		ResponseResult responseResult = new ResponseResult();
		
		if(null != user) {
			try {
				this.userDao.updateUserById(user);
				
				responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
				responseResult.setMessage("更新【用户】 - 成功。");
			} catch (Exception e) {
				LOGGER.error("根据【ID】更新【用户】 - 失败！", e);
				
				responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
				responseResult.setMessage("更新【用户】 - 失败！");
			}
		}
		
		return responseResult;
	}

	@Override
	public ResponseResult deleteUserById(long id) {
		LOGGER.info("id = " + id);
		ResponseResult responseResult = new ResponseResult();
		
		try {
			this.userDao.deleteUserById(id);
			
			responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
			responseResult.setMessage("删除【用户】 - 成功。");
		} catch (Exception e) {
			LOGGER.error("根据【ID】删除【用户】 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("删除【用户】 - 失败！");
		}
		
		return responseResult;
	}
}